Arrays, Objects, and Destructuring in JavaScript for React Native
Course: React Native Training
Topic: Arrays, Objects, and Destructuring
Course Link: React Native Training at JustAcademy
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to Arrays, Objects, and Destructuring
Arrays, objects, and destructuring are essential JavaScript concepts used in React Native application development. They help developers organize information, represent real-world entities, access data efficiently, and write clean, readable code.
React Native applications frequently work with information such as user profiles, product catalogs, shopping carts, API responses, messages, notifications, and application settings. Arrays store collections of values, objects represent related properties, and destructuring extracts specific values from arrays and objects into variables.
1.1 What Is an Array?
An array is an ordered collection of values stored in a single variable. The values can be strings, numbers, Booleans, objects, other arrays, or a mixture of data types.
const courses = ["JavaScript", "React", "React Native"];
console.log(courses[0]); // JavaScript
console.log(courses[1]); // React
console.log(courses[2]); // React Native
1.2 What Is an Object?
An object stores related information as key-value pairs. Each key identifies a property, and its value contains the associated data.
const student = {
name: "Riya",
age: 22,
course: "React Native"
};
console.log(student.name); // Riya
console.log(student.age); // 22
1.3 What Is Destructuring?
Destructuring is a JavaScript syntax that extracts values from arrays or properties from objects and assigns them to variables.
const student = {
name: "Riya",
age: 22
};
const { name, age } = student;
console.log(name); // Riya
console.log(age); // 22
Destructuring is particularly useful in React Native when accessing component props, state values, API data, navigation parameters, and hook results.
1.4 Learning Objectives
- Understand arrays and their indexes.
- Create, access, update, and process arrays.
- Use common array methods such as
map(), filter(), find(), and reduce().
- Understand JavaScript objects and their properties.
- Add, update, remove, and access object properties.
- Use object and array destructuring.
- Apply default values, aliases, nested destructuring, and rest syntax.
- Use arrays, objects, and destructuring in React Native components.
- Manage arrays and objects correctly when working with React state.
2. Understanding Arrays in JavaScript
An array is a data structure that stores multiple values in a particular order. Arrays are useful when an application needs to maintain a collection of related items.
2.1 Creating an Array
const names = ["Aman", "Riya", "Neha"];
const ages = [20, 22, 25];
const scores = [85, 90, 78];
const mixedData = ["React Native", 100, true];
console.log(names);
console.log(ages);
console.log(scores);
console.log(mixedData);
2.2 Creating an Empty Array
const tasks = [];
const products = [];
console.log(tasks.length); // 0
console.log(products.length); // 0
Empty arrays are common when initializing application data or state that will later receive information from user input or an API.
2.3 Array Indexes
Array indexes begin at zero. The first element has index 0, the second has index 1, and the final element has an index equal to the array's length minus one.
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits[2]); // Mango
2.4 Accessing an Element That Does Not Exist
const fruits = ["Apple", "Banana"];
console.log(fruits[5]); // undefined
JavaScript returns undefined when reading an array index that does not contain an element. Check the array length or validate the index when the value is required.
2.5 Checking Array Length
const courses = ["HTML", "CSS", "JavaScript", "React"];
console.log(courses.length); // 4
The length property is useful for determining how many elements an array contains and for checking whether a list is empty.
3. Accessing and Updating Array Elements
Array elements can be read and changed using their indexes. JavaScript arrays are mutable, which means their elements can be modified.
3.1 Accessing Elements
const colors = ["Red", "Green", "Blue"];
const firstColor = colors[0];
const lastColor = colors[colors.length - 1];
console.log(firstColor); // Red
console.log(lastColor); // Blue
3.2 Updating an Element
const fruits = ["Apple", "Banana", "Mango"];
fruits[1] = "Orange";
console.log(fruits);
// ["Apple", "Orange", "Mango"]
Although an array declared with const can have its elements modified, the variable cannot be reassigned to a completely different array.
3.3 Reassigning a const Array
const numbers = [1, 2, 3];
// This is valid:
numbers[0] = 10;
// This causes an error:
// numbers = [4, 5, 6];
In React applications, direct mutation of arrays held in state should generally be avoided. Instead, create a new array and update the state using its setter function.
4. Common Array Methods
JavaScript provides built-in array methods that simplify adding, removing, searching, transforming, and processing elements.
4.1 push()
The push() method adds one or more elements to the end of an array and returns the new length.
const fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);
// ["Apple", "Banana", "Mango"]
4.2 pop()
The pop() method removes the last element and returns the removed value.
const fruits = ["Apple", "Banana", "Mango"];
const removedFruit = fruits.pop();
console.log(removedFruit); // Mango
console.log(fruits); // ["Apple", "Banana"]
4.3 unshift()
The unshift() method adds one or more elements to the beginning of an array.
const numbers = [2, 3, 4];
numbers.unshift(1);
console.log(numbers); // [1, 2, 3, 4]
4.4 shift()
The shift() method removes the first element and returns it.
const numbers = [10, 20, 30];
const removedNumber = numbers.shift();
console.log(removedNumber); // 10
console.log(numbers); // [20, 30]
4.5 includes()
The includes() method checks whether an array contains a particular value and returns a Boolean.
const technologies = ["JavaScript", "React", "React Native"];
console.log(technologies.includes("React")); // true
console.log(technologies.includes("Python")); // false
4.6 indexOf()
The indexOf() method returns the first index of a matching value. It returns -1 if the value is not found.
const colors = ["Red", "Green", "Blue"];
console.log(colors.indexOf("Green")); // 1
console.log(colors.indexOf("Black")); // -1
4.7 slice()
The slice() method returns a shallow copy of a selected section of an array without modifying the original array.
const numbers = [10, 20, 30, 40, 50];
const selectedNumbers = numbers.slice(1, 4);
console.log(selectedNumbers); // [20, 30, 40]
console.log(numbers); // [10, 20, 30, 40, 50]
The ending index is excluded. In the example, index 4 is not included in the result.
4.8 splice()
The splice() method adds, removes, or replaces elements in an array by modifying the original array.
const fruits = ["Apple", "Banana", "Mango"];
fruits.splice(1, 1, "Orange");
console.log(fruits);
// ["Apple", "Orange", "Mango"]
Here, the method starts at index 1, removes one element, and inserts "Orange".
5. Processing Arrays with map(), filter(), find(), and reduce()
Array iteration methods are especially important in React Native because applications often need to transform API responses, filter lists, calculate totals, and render collections of data.
5.1 map()
The map() method applies a callback to every array element and returns a new array containing the results.
const numbers = [1, 2, 3, 4];
const doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers); // [2, 4, 6, 8]
5.2 filter()
The filter() method returns a new array containing only the elements that satisfy a condition.
const prices = [100, 250, 500, 750, 1000];
const expensiveItems = prices.filter(price => price >= 500);
console.log(expensiveItems); // [500, 750, 1000]
5.3 find()
The find() method returns the first element that satisfies a condition. If no element matches, it returns undefined.
const users = [
{ id: 1, name: "Aman" },
{ id: 2, name: "Riya" },
{ id: 3, name: "Neha" }
];
const selectedUser = users.find(user => user.id === 2);
console.log(selectedUser);
// { id: 2, name: "Riya" }
5.4 findIndex()
The findIndex() method returns the index of the first element satisfying a condition, or -1 if there is no match.
const numbers = [10, 20, 30, 40];
const index = numbers.findIndex(number => number === 30);
console.log(index); // 2
5.5 reduce()
The reduce() method combines array elements into a single result. It is often used for totals, counts, summaries, and grouped data.
const prices = [100, 200, 300];
const total = prices.reduce(
(sum, price) => sum + price,
0
);
console.log(total); // 600
5.6 some()
The some() method returns true if at least one array element satisfies a condition.
const scores = [35, 48, 72, 90];
const hasHighScore = scores.some(score => score >= 85);
console.log(hasHighScore); // true
5.7 every()
The every() method returns true only when all elements satisfy the condition. For an empty array, it returns true.
const scores = [75, 80, 90];
const allPassed = scores.every(score => score >= 40);
console.log(allPassed); // true
5.8 Array Methods Comparison
| Method |
Purpose |
Result |
push() |
Add items at the end |
New array length |
pop() |
Remove the last item |
Removed item |
slice() |
Copy a portion of an array |
New array |
splice() |
Add or remove items in place |
Array of removed items |
includes() |
Check for a value |
Boolean |
map() |
Transform each item |
New array |
filter() |
Select matching items |
New array |
find() |
Find first matching item |
Item or undefined |
reduce() |
Combine values |
Accumulated result |
some() |
Check whether any item matches |
Boolean |
every() |
Check whether all items match |
Boolean |
6. Understanding Objects in JavaScript
An object is a collection of properties. Each property has a key and a value. Objects help represent entities that contain multiple related pieces of information.
6.1 Creating an Object
const student = {
name: "Riya",
age: 22,
course: "React Native",
isEnrolled: true
};
console.log(student);
6.2 Object Properties
In this object, name, age, course, and isEnrolled are property keys. Their associated values are a string, number, string, and Boolean respectively.
6.3 Accessing Properties with Dot Notation
const student = {
name: "Riya",
age: 22
};
console.log(student.name); // Riya
console.log(student.age); // 22
6.4 Accessing Properties with Bracket Notation
Bracket notation is useful when a property name is stored in a variable or contains characters that cannot be used directly in dot notation.
const student = {
name: "Riya",
age: 22
};
const propertyName = "name";
console.log(student[propertyName]); // Riya
console.log(student["age"]); // 22
6.5 Updating an Object Property
const student = {
name: "Riya",
age: 22
};
student.age = 23;
console.log(student.age); // 23
6.6 Adding a New Property
const student = {
name: "Riya"
};
student.course = "React Native";
console.log(student);
// { name: "Riya", course: "React Native" }
6.7 Removing a Property
const student = {
name: "Riya",
age: 22,
course: "React Native"
};
delete student.age;
console.log(student);
// { name: "Riya", course: "React Native" }
Direct property changes are valid JavaScript. However, when an object is stored in React state, use a state update that creates a new object rather than directly modifying the existing state object.
7. Object Methods and Shorthand Properties
Objects can contain functions as property values. These functions are often called methods.
7.1 Creating an Object Method
const user = {
name: "Aman",
greet() {
return `Hello, ${this.name}!`;
}
};
console.log(user.greet()); // Hello, Aman!
In this example, this.name refers to the object's name property when the method is called as user.greet().
7.2 Property Shorthand
When a variable name is the same as an object property name, JavaScript allows a shorter object syntax.
const name = "Riya";
const age = 22;
const student = {
name,
age
};
console.log(student);
// { name: "Riya", age: 22 }
7.3 Computed Property Names
Computed property names allow a variable or expression to determine the name of a property.
const property = "course";
const student = {
name: "Riya",
[property]: "React Native"
};
console.log(student.course); // React Native
8. Nested Arrays and Objects
Real-world application data frequently contains arrays of objects or objects with nested arrays and objects. For example, a user may have an address object and a list of purchased products.
8.1 Object Containing Another Object
const user = {
name: "Aman",
address: {
city: "Mumbai",
country: "India"
}
};
console.log(user.address.city); // Mumbai
console.log(user.address.country); // India
8.2 Object Containing an Array
const student = {
name: "Riya",
skills: ["JavaScript", "React", "React Native"]
};
console.log(student.skills[0]); // JavaScript
console.log(student.skills[2]); // React Native
8.3 Array Containing Objects
const products = [
{ id: 1, name: "Mouse", price: 500 },
{ id: 2, name: "Keyboard", price: 1200 },
{ id: 3, name: "Monitor", price: 8000 }
];
console.log(products[0].name); // Mouse
console.log(products[1].price); // 1200
8.4 Updating a Nested Value
When updating nested data in React state, copy each object along the path to the property being changed.
const user = {
name: "Aman",
address: {
city: "Mumbai",
country: "India"
}
};
const updatedUser = {
...user,
address: {
...user.address,
city: "Pune"
}
};
console.log(updatedUser.address.city); // Pune
console.log(user.address.city); // Mumbai
This example creates a new outer object and a new address object, leaving the original objects unchanged.
9. Introduction to Destructuring
Destructuring allows values to be extracted from arrays or objects into variables using concise syntax. It improves readability and reduces repeated property access.
9.1 Without Destructuring
const user = {
name: "Aman",
age: 24,
city: "Mumbai"
};
const name = user.name;
const age = user.age;
const city = user.city;
console.log(name, age, city);
9.2 With Destructuring
const user = {
name: "Aman",
age: 24,
city: "Mumbai"
};
const { name, age, city } = user;
console.log(name, age, city);
Both examples extract the same values. Destructuring is more concise when several properties are required.
9.3 Two Main Types of Destructuring
| Type |
Syntax |
Purpose |
| Array destructuring |
const [first, second] = values; |
Extract values by position. |
| Object destructuring |
const { name, age } = user; |
Extract values by property name. |
10. Array Destructuring
Array destructuring extracts array elements based on their positions. The variable names are chosen by the developer, and the order determines which values are assigned.
10.1 Basic Array Destructuring
const colors = ["Red", "Green", "Blue"];
const [first, second, third] = colors;
console.log(first); // Red
console.log(second); // Green
console.log(third); // Blue
10.2 Skipping Array Elements
Commas can be used to skip elements that are not needed.
const numbers = [10, 20, 30, 40];
const [first, , third] = numbers;
console.log(first); // 10
console.log(third); // 30
10.3 Using Default Values
A default value is used when the corresponding array element is undefined.
const colors = ["Red"];
const [first, second = "Green"] = colors;
console.log(first); // Red
console.log(second); // Green
10.4 Swapping Variables
Array destructuring can swap two variables without using a temporary variable.
let first = "A";
let second = "B";
[first, second] = [second, first];
console.log(first); // B
console.log(second); // A
10.5 Rest Syntax in Array Destructuring
The rest syntax ... collects the remaining elements into a new array. It must appear at the end of a destructuring pattern.
const numbers = [10, 20, 30, 40, 50];
const [first, second, ...remaining] = numbers;
console.log(first); // 10
console.log(second); // 20
console.log(remaining); // [30, 40, 50]
10.6 Destructuring Function Results
A function can return an array, and the caller can use destructuring to assign the returned values to variables.
function getCoordinates() {
return [19.0760, 72.8777];
}
const [latitude, longitude] = getCoordinates();
console.log(latitude);
console.log(longitude);
11. Object Destructuring
Object destructuring extracts property values by matching property names. Unlike array destructuring, the position of a property in the object does not determine the variable assignment.
11.1 Basic Object Destructuring
const user = {
name: "Riya",
age: 22,
city: "Mumbai"
};
const { name, age } = user;
console.log(name); // Riya
console.log(age); // 22
11.2 Extracting a Property with an Alias
An alias allows a property to be assigned to a variable with a different name.
const user = {
name: "Riya",
age: 22
};
const { name: userName, age: userAge } = user;
console.log(userName); // Riya
console.log(userAge); // 22
In this example, name is the object property, and userName is the local variable. The alias syntax does not rename the original property.
11.3 Default Values in Object Destructuring
A default value is used when the property is missing or its value is undefined.
const user = {
name: "Aman"
};
const { name, city = "Mumbai" } = user;
console.log(name); // Aman
console.log(city); // Mumbai
A default value does not replace an explicit null value.
const settings = {
theme: null
};
const { theme = "light" } = settings;
console.log(theme); // null
11.4 Renaming a Property and Providing a Default
const user = {
name: "Neha"
};
const {
name: displayName,
role: userRole = "Learner"
} = user;
console.log(displayName); // Neha
console.log(userRole); // Learner
11.5 Nested Object Destructuring
Nested destructuring extracts values from properties that contain other objects.
const user = {
name: "Aman",
address: {
city: "Mumbai",
country: "India"
}
};
const {
address: { city, country }
} = user;
console.log(city); // Mumbai
console.log(country); // India
The variable address is not created by this pattern. To obtain both the nested object and its properties, destructure them separately or include address in the outer pattern.
const {
address,
address: { city }
} = user;
console.log(address);
console.log(city);
11.6 Rest Properties in Objects
The object rest syntax collects remaining enumerable own properties that have not already been selected.
const user = {
name: "Riya",
age: 22,
city: "Mumbai",
course: "React Native"
};
const { name, ...otherDetails } = user;
console.log(name); // Riya
console.log(otherDetails);
// { age: 22, city: "Mumbai", course: "React Native" }
12. Destructuring Function Parameters
Functions can destructure arrays or objects directly in their parameter lists. This is useful when a function receives a structured collection of options or a React component receives props.
12.1 Object Destructuring in Function Parameters
function displayUser({ name, age }) {
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
}
const user = {
name: "Aman",
age: 24
};
displayUser(user);
12.2 Default Values in Function Parameters
function displayUser({ name = "Guest", city = "Unknown" } = {}) {
console.log(name);
console.log(city);
}
displayUser({ name: "Riya" });
displayUser();
The default parameter = {} allows the function to be called without an argument. Without an appropriate default, destructuring an undefined parameter would cause an error.
12.3 Array Destructuring in Function Parameters
function displayCoordinates([latitude, longitude]) {
console.log("Latitude:", latitude);
console.log("Longitude:", longitude);
}
displayCoordinates([19.0760, 72.8777]);
13. Spread Syntax and Rest Syntax
The spread and rest syntaxes both use three dots, ..., but they serve different purposes. Spread expands an iterable or object properties in a suitable context, while rest gathers remaining values into an array or object.
13.1 Spread with Arrays
const first = [1, 2, 3];
const second = [4, 5, 6];
const combined = [...first, ...second];
console.log(combined);
// [1, 2, 3, 4, 5, 6]
13.2 Copying an Array
const original = ["React", "React Native"];
const copied = [...original];
console.log(copied); // ["React", "React Native"]
The copy is shallow. If the array contains objects or nested arrays, those nested references are shared between the original and copied arrays.
13.3 Spread with Objects
const user = {
name: "Aman",
age: 24
};
const updatedUser = {
...user,
age: 25,
city: "Mumbai"
};
console.log(updatedUser);
// { name: "Aman", age: 25, city: "Mumbai" }
When the same property appears more than once, the later value takes precedence in the resulting object.
13.4 Rest Parameters in Functions
function calculateTotal(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
console.log(calculateTotal(10, 20, 30)); // 60
13.5 Spread Versus Rest
| Feature |
Spread |
Rest |
| Purpose |
Expands values or properties |
Collects remaining values |
| Common array example |
[...numbers] |
const [first, ...rest] = numbers |
| Common object example |
{ ...user } |
const { name, ...details } = user |
| Function example |
fn(...args) |
function fn(...args) {} |
14. Arrays and Objects in React Native Components
React Native components commonly receive arrays and objects through props, use them to build interfaces, and manage them as state. Understanding their structure makes it easier to write reusable components.
14.1 Passing an Object as a Prop
import { View, Text } from "react-native";
const UserCard = ({ user }) => {
return (
<View>
<Text>Name: {user.name}</Text>
<Text>City: {user.city}</Text>
</View>
);
};
const App = () => {
const user = {
name: "Riya",
city: "Mumbai"
};
return <UserCard user={user} />;
};
export default App;
14.2 Destructuring Props Directly
Instead of repeatedly writing props.name or props.city, a component can destructure the properties directly in its function parameter.
import { View, Text } from "react-native";
const UserCard = ({ name, city }) => {
return (
<View>
<Text>Name: {name}</Text>
<Text>City: {city}</Text>
</View>
);
};
const App = () => {
return (
<UserCard name="Riya" city="Mumbai" />
);
};
export default App;
14.3 Passing an Array as a Prop
import { View, Text } from "react-native";
const SkillList = ({ skills }) => {
return (
<View>
{skills.map(skill => (
<Text key={skill}>{skill}</Text>
))}
</View>
);
};
const App = () => {
const skills = ["JavaScript", "React", "React Native"];
return <SkillList skills={skills} />;
};
export default App;
Use a stable, unique key for every rendered item. In this example, each skill string is unique, so the skill itself can be used as the key. For data that may contain duplicate labels, use a unique identifier.
15. Rendering Arrays of Objects in React Native
Applications frequently receive arrays of objects from APIs. Each object represents an item, such as a product, user, order, or message.
15.1 Product Data
const products = [
{ id: "p1", name: "Mouse", price: 500 },
{ id: "p2", name: "Keyboard", price: 1200 },
{ id: "p3", name: "Monitor", price: 8000 }
];
15.2 Displaying Data with map()
import { View, Text } from "react-native";
const ProductList = () => {
const products = [
{ id: "p1", name: "Mouse", price: 500 },
{ id: "p2", name: "Keyboard", price: 1200 },
{ id: "p3", name: "Monitor", price: 8000 }
];
return (
<View>
{products.map(product => (
<View key={product.id}>
<Text>{product.name}</Text>
<Text>Price: ₹{product.price}</Text>
</View>
))}
</View>
);
};
export default ProductList;
15.3 Destructuring Each Product
import { View, Text } from "react-native";
const products = [
{ id: "p1", name: "Mouse", price: 500 },
{ id: "p2", name: "Keyboard", price: 1200 }
];
const ProductList = () => {
return (
<View>
{products.map(({ id, name, price }) => (
<View key={id}>
<Text>{name}</Text>
<Text>Price: ₹{price}</Text>
</View>
))}
</View>
);
};
export default ProductList;
Destructuring the callback parameter makes the code shorter by extracting id, name, and price from each product object.
16. Using FlatList for Larger Collections
For larger or changing collections, React Native's FlatList component is generally preferred over rendering every item with map() inside a regular container. It supports efficient list rendering and provides features such as key extraction, separators, and empty-state content.
16.1 FlatList Example
import { View, Text, FlatList } from "react-native";
const products = [
{ id: "1", name: "Mouse", price: 500 },
{ id: "2", name: "Keyboard", price: 1200 },
{ id: "3", name: "Monitor", price: 8000 }
];
const ProductScreen = () => {
return (
<FlatList
data={products}
keyExtractor={item => item.id}
renderItem={({ item }) => {
const { name, price } = item;
return (
<View>
<Text>{name}</Text>
<Text>Price: ₹{price}</Text>
</View>
);
}}
ListEmptyComponent={
<Text>No products available.</Text>
}
/>
);
};
export default ProductScreen;
16.2 Understanding the Important Props
| Prop |
Purpose |
data |
Provides the array of items to display. |
renderItem |
Defines how each item is rendered. |
keyExtractor |
Returns a stable unique key for each item. |
ListEmptyComponent |
Displays content when the data array is empty. |
ListHeaderComponent |
Displays content before the list items. |
ListFooterComponent |
Displays content after the list items. |
17. Managing Arrays and Objects with React State
React state can store arrays and objects. When state changes, React can render the component again to reflect the new data. The important rule is to create a new array or object when updating state rather than mutating the existing state value.
17.1 Storing an Array in useState
import { useState } from "react";
import { View, Text, Button } from "react-native";
const TaskScreen = () => {
const [tasks, setTasks] = useState(["Learn JavaScript"]);
const addTask = () => {
setTasks(previousTasks => [
...previousTasks,
"Practice React Native"
]);
};
return (
<View>
{tasks.map((task, index) => (
<Text key={`${index}-${task}`}>{task}</Text>
))}
<Button title="Add Task" onPress={addTask} />
</View>
);
};
export default TaskScreen;
This example demonstrates adding an item using a new array. In a production application, each task should ideally have its own stable ID rather than using its index as part of the key.
17.2 Adding an Object to an Array
import { useState } from "react";
import { View, Text, Button } from "react-native";
const TaskScreen = () => {
const [tasks, setTasks] = useState([
{ id: "1", title: "Learn JavaScript" }
]);
const addTask = () => {
const newTask = {
id: String(Date.now()),
title: "Practice React Native"
};
setTasks(previousTasks => [
...previousTasks,
newTask
]);
};
return (
<View>
{tasks.map(({ id, title }) => (
<Text key={id}>{title}</Text>
))}
<Button title="Add Task" onPress={addTask} />
</View>
);
};
export default TaskScreen;
The example generates an ID for demonstration. In production, use a reliable unique-ID strategy appropriate for the application rather than assuming timestamps are always unique.
17.3 Updating an Object in an Array
const tasks = [
{ id: "1", title: "Learn JavaScript", completed: false },
{ id: "2", title: "Practice React Native", completed: false }
];
const updatedTasks = tasks.map(task =>
task.id === "1"
? { ...task, completed: true }
: task
);
console.log(updatedTasks);
The map() method creates a new array and replaces the matching task with a new object. The other task objects are retained.
17.4 Removing an Object from an Array
const tasks = [
{ id: "1", title: "Learn JavaScript" },
{ id: "2", title: "Practice React Native" }
];
const updatedTasks = tasks.filter(task => task.id !== "1");
console.log(updatedTasks);
// [{ id: "2", title: "Practice React Native" }]
17.5 Updating an Object in useState
import { useState } from "react";
import { View, Text, Button } from "react-native";
const ProfileScreen = () => {
const [user, setUser] = useState({
name: "Riya",
city: "Mumbai"
});
const updateCity = () => {
setUser(previousUser => ({
...previousUser,
city: "Pune"
}));
};
return (
<View>
<Text>Name: {user.name}</Text>
<Text>City: {user.city}</Text>
<Button title="Update City" onPress={updateCity} />
</View>
);
};
export default ProfileScreen;
The spread operator preserves existing properties while replacing the city value. The state setter receives a new object, allowing React to recognize the update.
18. Destructuring React Native Props and Hooks
Destructuring is widely used in React Native because components often receive objects as props and hooks often return arrays.
18.1 Destructuring Component Props
const WelcomeMessage = ({ name, course }) => {
return (
<Text>
Welcome {name} to {course}.
</Text>
);
};
18.2 Destructuring useState
The useState() hook returns an array containing the current state value and a function that updates it. Array destructuring makes these values easy to assign.
import { useState } from "react";
import { View, Text, Button } from "react-native";
const Counter = () => {
const [count, setCount] = useState(0);
return (
<View>
<Text>Count: {count}</Text>
<Button
title="Increase"
onPress={() => setCount(previousCount => previousCount + 1)}
/>
</View>
);
};
export default Counter;
Here, count stores the current state value, and setCount is the function used to request an update.
18.3 Destructuring useState with an Object
import { useState } from "react";
import { View, Text, Button } from "react-native";
const ProfileScreen = () => {
const [user, setUser] = useState({
name: "Aman",
age: 24
});
const increaseAge = () => {
setUser(previousUser => ({
...previousUser,
age: previousUser.age + 1
}));
};
const { name, age } = user;
return (
<View>
<Text>Name: {name}</Text>
<Text>Age: {age}</Text>
<Button title="Increase Age" onPress={increaseAge} />
</View>
);
};
export default ProfileScreen;
19. Handling API Responses with Arrays and Objects
React Native applications often receive JSON data from web APIs. JSON objects are commonly represented as JavaScript objects, while JSON arrays are represented as JavaScript arrays. Destructuring helps access the required values after the response has been validated and processed.
19.1 Example API Response
const responseData = {
success: true,
message: "Products loaded",
data: [
{ id: "1", name: "Mouse", price: 500 },
{ id: "2", name: "Keyboard", price: 1200 }
]
};
19.2 Extracting API Values
const { success, message, data: products } = responseData;
console.log(success); // true
console.log(message); // Products loaded
console.log(products); // Array of products
19.3 Processing the Response
const affordableProducts = products.filter(
({ price }) => price < 1000
);
console.log(affordableProducts);
// [{ id: "1", name: "Mouse", price: 500 }]
19.4 Practical Fetch Example
async function loadUsers() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error("Failed to load users");
}
const users = await response.json();
const userSummaries = users.map(({ id, name, email }) => ({
id,
name,
email
}));
return userSummaries;
} catch (error) {
console.error("Unable to load users:", error);
return [];
}
}
This function checks the HTTP response, parses the JSON data, and transforms the returned user objects into smaller summaries. In a complete React Native component, the result would normally be stored in state and displayed in a list.
20. Optional Chaining and Safe Data Access
When working with nested objects, a property or parent object may be missing. Optional chaining, written as ?., allows safe access to nested properties without throwing an error when an intermediate value is null or undefined.
20.1 Accessing a Nested Property Safely
const user = {
name: "Riya"
};
console.log(user.address?.city); // undefined
20.2 Optional Chaining with Arrays
const response = {
data: {
products: [
{ id: "1", name: "Mouse" }
]
}
};
console.log(response.data?.products?.[0]?.name); // Mouse
20.3 Using Nullish Coalescing
The nullish coalescing operator ?? provides a fallback only when the left-hand value is null or undefined.
const user = {
name: "",
city: null
};
const displayName = user.name ?? "Guest";
const displayCity = user.city ?? "Unknown";
console.log(displayName); // ""
console.log(displayCity); // Unknown
Unlike ||, the ?? operator preserves valid falsy values such as an empty string, zero, and false.
21. Shallow Copies, References, and Immutability
Arrays and objects are reference values in JavaScript. Assigning an object or array to another variable does not automatically create an independent copy; both variables may refer to the same underlying value.
21.1 Understanding Object References
const original = {
name: "Aman"
};
const copiedReference = original;
copiedReference.name = "Riya";
console.log(original.name); // Riya
Both variables reference the same object, so changing the object through either reference affects the same data.
21.2 Creating a Shallow Copy with Spread
const original = {
name: "Aman",
age: 24
};
const copiedObject = {
...original
};
copiedObject.name = "Riya";
console.log(original.name); // Aman
console.log(copiedObject.name); // Riya
21.3 Shallow Copy Limitation
Spread syntax copies only the outer level. Nested objects remain shared unless they are copied separately.
const original = {
name: "Aman",
address: {
city: "Mumbai"
}
};
const copied = {
...original
};
copied.address.city = "Pune";
console.log(original.address.city); // Pune
To update nested state safely, create new copies at each changed level.
const updated = {
...original,
address: {
...original.address,
city: "Delhi"
}
};
21.4 Why Immutability Matters in React Native
- It helps React detect state changes reliably.
- It prevents accidental changes to existing data.
- It makes component behavior easier to reason about.
- It supports predictable state updates.
- It simplifies debugging and testing.
22. Common Mistakes and Troubleshooting
| Mistake |
Reason |
Solution |
| Using the wrong array index |
Array indexes start at zero |
Check the required index and array length. |
| Accessing a missing property |
The property may not exist |
Validate the data or use optional chaining. |
| Expecting destructuring to create a property |
Object destructuring reads existing property values |
Use the correct property name or provide a default. |
| Confusing property aliases |
The source property and local variable names differ |
Remember that { name: userName } reads name into userName. |
| Using a default for null |
Defaults apply to undefined, not null |
Use ?? when null should also trigger a fallback. |
| Mutating React state directly |
The existing array or object is changed in place |
Create a new value and pass it to the state setter. |
| Using duplicate list keys |
Multiple elements have the same key |
Use stable, unique IDs for list items. |
| Assuming spread creates a deep copy |
Spread performs a shallow copy |
Copy nested structures where updates are needed. |
| Calling map on undefined |
Data may not have loaded yet |
Initialize the array or validate the response before mapping. |
| Using splice on state arrays |
splice modifies the original array |
Use methods such as filter, map, or a copied array for state updates. |
23. Best Practices
- Use arrays to represent ordered collections of items.
- Use objects to group related properties under meaningful names.
- Prefer
const when a variable does not need reassignment.
- Use descriptive names for array variables and object properties.
- Use
map() to transform data and render arrays of elements.
- Use
filter() to select matching elements without changing the original array.
- Use object destructuring to make component props easier to read.
- Use array destructuring to access hook results such as
useState().
- Provide default values when data may be missing.
- Use optional chaining when nested values may be absent.
- Use spread syntax to create new arrays and objects during state updates.
- Remember that spread creates a shallow copy, not a deep copy.
- Give rendered React Native list items stable and unique keys.
- Use
FlatList for larger or changing lists.
- Validate API responses and handle loading, empty, and error states.
24. Hands-On Exercises
Exercise 1: Create a Course Array
Create an array containing five course names. Print the first and last items and display the total number of courses.
Exercise 2: Update an Array
Create an array of fruits. Add a new fruit, remove the last fruit, and print the resulting array.
Exercise 3: Filter Numbers
Create an array of numbers and use filter() to return only values greater than 50.
Exercise 4: Transform an Array
Create an array of prices and use map() to calculate a 10% increase for every price.
Exercise 5: Create a User Object
Create a user object with a name, age, email, and city. Access the properties with dot notation and bracket notation.
Exercise 6: Object Destructuring
Extract the name and email properties from a user object. Rename the name variable to displayName.
Exercise 7: Array Destructuring
Create an array of five numbers. Extract the first number, skip the second, extract the third, and collect the remaining numbers using rest syntax.
Exercise 8: Nested Object
Create an object containing a user's name and an address object with city and country properties. Use nested destructuring to extract the city and country.
Exercise 9: Update React State
Create a React Native component that stores a user object in state. Add a button that updates the city by creating a new object.
Exercise 10: Product List
Create an array of product objects containing IDs, names, and prices. Render the products using FlatList and destructure the item properties in renderItem.
25. Mini Project: React Native Product Catalog
Project Objective: Build a simple product catalog that uses arrays, objects, destructuring, filtering, and React Native list rendering.
Project Requirements
- Create an array of product objects.
- Each product must have a unique ID, name, price, and availability status.
- Use destructuring to extract product properties.
- Display the products using
FlatList.
- Filter the array to find available products.
- Calculate the total price of available products using
reduce().
- Display a message when no products are available.
- Use stable keys for every list item.
Sample Implementation
import { View, Text, FlatList } from "react-native";
const products = [
{ id: "1", name: "Mouse", price: 500, available: true },
{ id: "2", name: "Keyboard", price: 1200, available: false },
{ id: "3", name: "Headphones", price: 1800, available: true }
];
const availableProducts = products.filter(
({ available }) => available
);
const totalPrice = availableProducts.reduce(
(total, { price }) => total + price,
0
);
const ProductCatalog = () => {
return (
<View>
<Text>Available Products: {availableProducts.length}</Text>
<Text>Total Price: ₹{totalPrice}</Text>
<FlatList
data={availableProducts}
keyExtractor={({ id }) => id}
renderItem={({ item: { name, price } }) => (
<View>
<Text>{name}</Text>
<Text>Price: ₹{price}</Text>
</View>
)}
ListEmptyComponent={
<Text>No products available.</Text>
}
/>
</View>
);
};
export default ProductCatalog;
Project Explanation
- The
products array stores product objects.
filter() selects products whose availability is true.
reduce() calculates the combined price of available products.
FlatList displays the selected product collection.
- Destructuring extracts the product ID, name, price, and availability values.
ListEmptyComponent displays a message when the filtered collection is empty.
26. Interview Questions and Answers
Q1. What is an array in JavaScript?
Answer: An array is an ordered collection of values stored in a single variable. Each element can be accessed using its index, starting from zero.
Q2. What is an object in JavaScript?
Answer: An object is a collection of properties represented as key-value pairs. It is useful for grouping related data such as user details or product information.
Q3. What is the difference between an array and an object?
Answer: Arrays are ordered collections generally accessed by numeric indexes. Objects store properties accessed by their keys.
Q4. What is array destructuring?
Answer: Array destructuring extracts elements from an array into variables according to their positions.
Q5. What is object destructuring?
Answer: Object destructuring extracts property values into variables by matching property names.
Q6. What is the difference between map() and filter()?
Answer: map() transforms every element and returns a new array. filter() returns a new array containing only the elements that satisfy a condition.
Q7. What is the difference between slice() and splice()?
Answer: slice() returns a selected portion without changing the original array. splice() modifies the original array by adding, removing, or replacing elements.
Q8. What is the spread operator?
Answer: Spread syntax, written as ..., expands values from an iterable or properties from an object in supported contexts. It is often used to copy arrays and objects.
Q9. What is the rest operator?
Answer: Rest syntax collects remaining values into an array or object. It is used in function parameters and array or object destructuring patterns.
Q10. What is the difference between spread and rest?
Answer: Spread expands values, while rest gathers remaining values into a collection. Their meaning depends on the context in which the syntax is used.
Q11. What is a shallow copy?
Answer: A shallow copy creates a new outer array or object, but nested objects and arrays are still shared references unless copied separately.
Q12. Why should React state arrays not be mutated directly?
Answer: Direct mutation can make changes difficult for React to detect and can lead to unpredictable behavior. Creating a new array or object and passing it to the state setter is the recommended approach.
Q13. How do you update an object in React state?
Answer: Use the state setter to create a new object, often with spread syntax, and replace the property that needs to change.
Q14. Why is destructuring useful in React Native?
Answer: It makes props, hook results, API responses, and object properties easier to access while keeping components concise and readable.
Q15. What is the purpose of FlatList?
Answer: FlatList renders collections of items efficiently in React Native and supports features such as unique keys, empty states, and list headers.
Q16. What happens when an array index does not exist?
Answer: Reading a missing array index generally returns undefined.
Q17. What is optional chaining?
Answer: Optional chaining, written as ?., safely accesses nested properties when an intermediate value may be null or undefined.
Q18. What is the difference between a default value and nullish coalescing?
Answer: Destructuring defaults apply when a value is undefined. The ?? operator provides a fallback when an expression evaluates to null or undefined.
27. Quick Revision Checklist
- Understand array creation, indexing, and length.
- Practice adding, removing, and updating array elements.
- Know the purpose of
map(), filter(), find(), and reduce().
- Understand object properties and dot and bracket notation.
- Practice adding, updating, and removing object properties.
- Understand nested arrays and objects.
- Use array destructuring to extract values by position.
- Use object destructuring to extract values by property name.
- Practice aliases, defaults, nested destructuring, and rest syntax.
- Understand the difference between spread and rest.
- Use arrays and objects as React Native props and state.
- Use immutable updates when changing React state.
- Render lists with stable keys and use
FlatList for larger collections.
- Handle missing data safely with defaults and optional chaining.
28. Recommended Learning Resources
29. Conclusion
Arrays, objects, and destructuring form an important foundation for JavaScript and React Native development. Arrays help manage collections of values, objects organize related properties, and destructuring makes data access more concise and readable.
These concepts are used throughout React Native applications, including component props, hook results, API responses, product lists, user profiles, and application state. Spread syntax, array methods, optional chaining, and immutable state updates help developers handle this data clearly and safely.
Practice by creating arrays of objects, filtering and transforming their values, destructuring the properties you need, and rendering the results with React Native components. Apply these techniques in small projects before using them in larger applications.
Continue Learning: Explore React Native Training | Register for a Demo